from flask import jsonify

class APIError(Exception):
    """API错误基类"""
    status_code = 500
    
    def __init__(self, message=None, status_code=None, payload=None):
        super().__init__()
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_response(self):
        """转换为响应"""
        response = {
            'status': 'error',
            'message': self.message or 'An error occurred'
        }
        if self.payload:
            response['data'] = self.payload
        return jsonify(response), self.status_code

class ValidationError(APIError):
    """验证错误"""
    status_code = 400
    
    def __init__(self, message=None, errors=None):
        if isinstance(message, dict):
            # 如果 message 是字典，将其作为 errors
            super().__init__(message="Validation failed", payload={'errors': message})
        else:
            super().__init__(
                message=message or "Validation failed",
                payload={'errors': errors} if errors else None
            )

class NotFoundError(APIError):
    """资源未找到错误"""
    status_code = 404

class ServiceError(APIError):
    """服务错误"""
    status_code = 500 